package com.sinosoft.hydra.um.services.component.dataimport.validators;

import com.sinosoft.hydra.um.services.component.dataimport.resolvers.ValidateResult;
import org.apache.commons.lang.StringUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 字符串的枚举验证，验证字符串是否在指定字符串范围内
 */
public class EnumStringValidator extends Validator{


    private Set<String> values;
    private String errorMsg;

    public EnumStringValidator(String... values) {
        this.values = new HashSet<String>(Arrays.asList(values));
    }

    public EnumStringValidator(Set<String> values, String errorMsg) {
        this.values = values;
        this.errorMsg = errorMsg;
    }

    public ValidateResult validate(Object obj) {
        if(obj == null){
            return ValidateResult.PASS();
        }
        try {
            String ss = (String)obj;
            if(!values.contains(ss)){
                if(errorMsg != null){
                    return ValidateResult.ERROR(errorMsg);
                }
                return ValidateResult.ERROR("数据可选值只能为" + StringUtils.join(values, ',') + "其中一个");
            }
        }catch (Exception ex){
            throw new ValidateException();
        }

        return ValidateResult.PASS();
    }
}
